import axios from 'axios'
import { Message } from 'view-design'
import cookieUse from '@/libs/cookie.js'
import router from '@/router'
import { escapeRequestArgument, escapeResponseArgument } from '@/libs/utils'

let tokenFlag = 0

axios.defaults.timeout = 60000;

// http request 拦截器
axios.interceptors.request.use(
  config => {
      let token = cookieUse.getCookie('desig-token') || ''
    if (token&&token!=='') {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = `${token}`;
    }
    escapeRequestArgument(config)
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
      let token = cookieUse.getCookie('desig-token') || ''
      let _res = response;
      escapeResponseArgument(response)
    if(response.data.code === -9599){  // 登录超时 跳转至登录页面
      let {current,pending} = router.history;
      if(tokenFlag === 0 && current.path !== '/login' && !current.meta.login && !(pending && pending.name == 'main')){
        Message.error({
          content:response.data.message,
          duration:2,
        })
        tokenFlag = 1
      }
      setTimeout(()=>{
        Message.destroy()
        window.openLogin(router)
        // router.push({
        //   path:'/login',
        // })
        cookieUse.setCookie('desig-token','',0)
        cookieUse.setCookie('Authorization','',0)
      },2000)
      _res.data.message = '';
      return _res;
    }else if(response.data.code === -9597){
      Message.error({
        content:response.data.message,
        duration:2,
      })
      setTimeout(()=>{
        cookieUse.setCookie('desig-token','',0)
        cookieUse.setCookie('Authorization','',0)
        window.openLogin(router)
        // router.push({
        //   path:'/login',
        // })
        
      },2000)
      return response;
    }else {
        if(sessionStorage.getItem('desig-rm') != 'true' || sessionStorage.getItem('desig-rm') === undefined){
            cookieUse.setCookie('desig-token',token,8)
            cookieUse.setCookie('Authorization',token,8)
        }
      return response;
    }
  },
  error => {
    if (error.code === 'ECONNABORTED') {
      Message.error({
        content: '接口超时，请稍后重试......',
        duration:2,
      })
      return Promise.reject('接口超时，请稍后重试......')
    }
    return Promise.reject(error)   // 返回接口返回的错误信息
  });

export default axios
